package com.ldy.chat.service.impl;

import com.ldy.chat.service.ChatCliService;
import com.ldy.chat.service.ChatServerService;
import com.ldy.chat.service.Msg;
import com.ldy.chat.service.User;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TJSONProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.apache.thrift.transport.layered.TFramedTransport;

/**
 * @Auther lin DeYU
 * @Date 2021/3/30
 */
public class ChatCliServiceImpl implements ChatCliService.Iface {

    private String centerIp="localhost";

    private int centerPort=9000;

    @Override
    public boolean sendMsg(User user, Msg msg) throws TException {
        TTransport tTransport= null;
        try {
            // 设置聊天服务器中心服务器地址
            tTransport = new TFramedTransport(new TSocket(this.centerIp,this.centerPort));
            // 设置数据传输协议,就是传输什么样的数据，怎样进行序列化和反序列化
            TProtocol tProtocol = new TJSONProtocol(tTransport);
            ChatServerService.Client chatServiceService=new ChatServerService.Client(tProtocol);
            // 开始数据传输通道
            tTransport.open();
            // 把消息传递到聊天室中心服务器进行消息转发打印发送消息
            System.out.println("发送消息 ："+ msg.content +" 到用户："+user.name+"=================================");
            boolean b = chatServiceService.forwardMsg(user, msg);
            tTransport.close();
            return b;
        } catch (TTransportException e) {
            e.printStackTrace();
        } catch (TException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接
            if(tTransport!=null){
                tTransport.close();
            }
        }
        return false;
    }

    @Override
    public boolean acceptMag(User user, Msg msg) throws TException {
        // 纯文本消息
        System.out.println("===========================================收到来自 "+user.name+" 消息: "+msg.content);
        return false;
    }

}
